﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using QuickManager.Code.SiteMgr;
using QuickManager.Code.SiteMgr.Model;
using Microsoft.Web.Administration;

namespace QuickManager.UI.SiteMgr
{
    public partial class SiteList : UserControl
    {

        private Panel panel;

        public SiteList(Panel panel)
        {
            InitializeComponent();

            this.panel = panel;
            this.LoadSiteGroup();
        }

        void LoadSiteGroup()
        {
            //站点分组列表
            this.treevWebsite.Nodes.Clear();
            foreach (GroupInfoModel group in SiteGroupManager.GetGroupList())
            {
                TreeNode node = new TreeNode()
                {
                    Text = group.GroupName,
                    Name = group.GroupID,
                    Tag = group
                };
                node.ContextMenuStrip = this.ctxMenuSiteGroup;
                this.treevWebsite.Nodes.Add(node);
            }
            this.LoadSite();
        }

        void LoadSite()
        {
            List<SiteInfoModel> siteList = SiteManager.GetSiteList();
            foreach (TreeNode group in this.treevWebsite.Nodes)
            {
                group.Nodes.Clear();
                siteList.ForEach((site) =>
                {
                    if ((group.Tag as GroupInfoModel).GroupID == site.GroupID)
                    {
                        TreeNode node = new TreeNode()
                        {
                            Text = string.Format("{0}({1})", site.SiteName, site.Port),
                            Tag = site,
                            ForeColor = IISMenager.GetWebSiteState(site.SiteName) == "运行中" ? Color.Green : Color.Red
                        };
                        node.ContextMenuStrip = this.ctxMenuSiteItem;
                        group.Nodes.Add(node);
                    }
                });
            }
        }

        #region 站点管理

        private void 新建分组ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TextInputForm inputForm = new TextInputForm("新建分组", "分组名称");
            inputForm.ShowDialog();
            if (inputForm.Tag != null)
            {
                SiteGroupManager.CreateGroup(new GroupInfoModel()
                {
                    GroupName = inputForm.Tag.ToString(),
                    GroupType = "1"
                });
                this.LoadSiteGroup();
            }
        }

        private void 新建站点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string siteID = SiteManager.CraeteSite(new SiteInfoModel()
            {
                SiteID = Guid.NewGuid().ToString(),
                SiteName = "未命名",
                GroupID = (this.treevWebsite.SelectedNode.Tag as GroupInfoModel).GroupID
            });

            if (string.IsNullOrEmpty(siteID) == false)
            {
                //重载
                this.LoadSite();
                this.treevWebsite.SelectedNode.Expand();
                this.treevWebsite.SelectedNode = this.treevWebsite.SelectedNode.Nodes.Cast<TreeNode>()
                    .Where(m => (m.Tag as SiteInfoModel).SiteID == siteID)
                    .FirstOrDefault();
                (this.panel.Controls.Find("SiteEdit", false).First() as SiteEdit).SetControlsReadOnly(false);
            }
        }

        private void treevWebsite_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if ((e.Node.Tag is SiteInfoModel) == false)
            {
                return;
            }

            //测试代码，加载编辑框
            this.panel.Controls.Clear();
            SiteEdit edit = new SiteEdit(UIMode.ReadMode, (e.Node.Tag as SiteInfoModel).SiteID)
            {
                Name = "SiteEdit",
                Dock = DockStyle.Fill
            };
            edit.OnSaved += new SiteEdit.AfterSave((siteInfo) =>
            {
                //修改名称
                e.Node.Text = string.Format("{0}({1})", siteInfo.SiteName, siteInfo.Port);
                e.Node.Tag = siteInfo;
                e.Node.ForeColor = IISMenager.GetWebSiteState(siteInfo.SiteName) == "运行中" ? Color.Green : Color.Red;
            });
            edit.OnStateChanged += new SiteEdit.StateChanged((running) =>
            {
                //启动或停止站点
                e.Node.ForeColor = running ? Color.Green : Color.Red;
            });
            this.panel.Controls.Add(edit);
        }

        #endregion

        private void 重新加载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SiteManager.InitSiteFromIIS();
            this.LoadSiteGroup();
            this.panel.Controls.Clear();
        }

        private void 删除站点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定删除选中站点？", "提示信息", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                TreeNode selected = this.treevWebsite.SelectedNode;
                TreeNode parent = selected.Parent;
                SiteManager.DeleteSite((selected.Tag as SiteInfoModel).SiteID);
                selected.Remove();
                if (parent.Nodes.Count == 0)
                {
                    this.panel.Controls.Clear();
                }
            }
        }

        private void 删除分组ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.treevWebsite.SelectedNode.Nodes.Count > 0)
            {
                MessageBox.Show("请先删除分组下的站点。", "提示信息", MessageBoxButtons.OK);
            }
            else
            {
                if ((this.treevWebsite.SelectedNode.Tag as GroupInfoModel).GroupID == Guid.Empty.ToString())
                {
                    MessageBox.Show("默认分组不允许删除。", "提示信息", MessageBoxButtons.OK);
                }
                else
                {
                    SiteGroupManager.DeleteGroup((this.treevWebsite.SelectedNode.Tag as GroupInfoModel).GroupID);
                    this.treevWebsite.SelectedNode.Remove();
                }
            }
        }

        private void 移动到分组ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmGroupSelect selected = new FrmGroupSelect();
            selected.ShowDialog();
            try
            {
                if (selected.Tag != null)
                {
                    string groupID = (selected.Tag as GroupInfoModel).GroupID;
                    if ((this.treevWebsite.SelectedNode.Parent.Tag as GroupInfoModel).GroupID != groupID)
                    {
                        SiteManager.ChangeGroup((this.treevWebsite.SelectedNode.Tag as SiteInfoModel).SiteID, groupID);
                        SiteInfoModel siteInfo = SiteManager.GetSiteInfo((this.treevWebsite.SelectedNode.Tag as SiteInfoModel).SiteID);
                        TreeNode appendNode = this.treevWebsite.Nodes.Cast<TreeNode>()
                             .ToList()
                             .FirstOrDefault(m => (m.Tag as GroupInfoModel).GroupID == groupID);
                        appendNode.Nodes.Add(new TreeNode()
                        {
                            Text = string.Format("{0}({1})", siteInfo.SiteName, siteInfo.Port),
                            Tag = siteInfo,
                            ForeColor = IISMenager.GetWebSiteState(siteInfo.SiteName) == "运行中" ? Color.Green : Color.Red
                        });
                        this.treevWebsite.SelectedNode.Remove();
                    }
                }

            }
            catch
            {
            }
            finally
            {
                selected.Dispose();
            }
        }

        private void treevWebsite_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                treevWebsite.SelectedNode = e.Node;
            }
        }

        private void 全部展开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treevWebsite.ExpandAll();
        }

        private void 全部缩起ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treevWebsite.CollapseAll();
        }
    }
}
